<template>
	<h1>登录页面</h1>
	<el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-width="80px">
		<el-form-item label="用户名" prop="username">
			<el-input v-model="loginForm.username"></el-input>
		</el-form-item>
		<el-form-item label="密码" prop="password">
			<el-input v-model="loginForm.password" type="password"></el-input>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="submitHandle()">登录</el-button>
		</el-form-item>
		<el-form-item>
			<el-button @click="resetHandle()">重置</el-button>
		</el-form-item>
		<el-form-item>
			<el-button @click="resetHandle2()">打印数据</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { loginApi } from '@/api/auth'
import { useUserStore } from '@/store/user-store'
const userStore = useUserStore()
const router = useRouter()
const redirect = ref('/')
const loginFormRef = ref()
const loginForm = reactive({
	username: 'admin',
	password: '123456'
})
const loginRules = {
	username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
	password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

watch(
	() => router.currentRoute.value,
	(newRoute: any) => {
		redirect.value = decodeURIComponent(newRoute.query?.redirect || '/')
	},
	{ immediate: true }
)

const submitHandle = () => {
	loginFormRef.value.validate((valid: boolean) => {
		if (valid) {
			userStore.clearAll()
			loginApi(loginForm).then(res => {
				console.log('登录数据: ', res.data)
				userStore.setData(res.data)
				ElMessage.success('登录成功')
				const redirectUrl = redirect.value || '/'
				router.push(redirectUrl)
			})
		}
	})
}
const resetHandle = () => {
	loginFormRef.value.resetFields()
}

const resetHandle2 = () => {
	console.log(userStore.tokenInfo)
}

</script>

<style scoped></style>
